<?php

use Illuminate\Database\Capsule\Manager as DB;

#前台基类
abstract class CCommonController extends CommonController
{

    public function init()
    {
        parent::init();
        $this->checkToken();
    }

    #中间件验证登陆标识
    private function checkToken()
    {
        $middle      = ucfirst($this->controller) . 'Middle';
        $midwarePath = middlewareFile($this->controller);
        if (file_exists($midwarePath)) {
            Yaf_Loader::import($midwarePath);
            if (class_exists($middle, false)) {
                $this->user = (new $middle)->handle($this->pageParam);
            }
            if (empty($this->user)) {
                throw new \Exception('未登陆.', 401);
            }
            $this->checkRole();
        }
    }

    private function checkRole()
    {
        #检查权限
        $allAuth = remember('role_' . $this->user->user_id, 3600, function () {
            $ownAuth = explode(',', DB::table('members_roles')->find($this->user->roles_id)->menu_ids);
            $rows    = DB::table('members_menus')->whereIn('id', array_values($ownAuth))->select('module', 'controller', 'actions')->get();
            $auth    = [];
            if ($rows->isNotEmpty()) {
                foreach ($rows as $k => $v) {
                    $allact = explode(',', $v->actions);
                    foreach ($allact as $action) {
                        if (!empty($v->module) && !empty($v->controller) && !empty($action)) {
                            array_push($auth, strtolower('/' . $v->module . '/' . $v->controller . '/' . $action));
                        }
                    }
                }
            }
            return $auth;
        });
        if (!in_array(strtolower('/' . $this->module . '/' . $this->controller . '/' . $this->action), $allAuth)) {
            throw new Exception('无访问权限.', 400);
        }
    }

}
